﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using AutoItX3Lib;
using CommonFunction;
using System.Runtime.InteropServices;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Security.Permissions;
using System.Linq;
using System.Diagnostics;


namespace Pokerist
{
    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    public partial class PokeristMain : Form
    {
        CancellationTokenSource tokenSource = null;
        Task taskPlayGame = null;

        const int MIN_WIDTH = 817;
        const int MAX_WIDTH = 1029;

        public PokeristMain()
        {
            InitializeComponent();

            Pokerist_Common.GameStatus = Pokerist_Common.GAME_STATUS.LOGIN;

            InitForm();
        }

        private void btnPlayGame_Click(object sender, EventArgs e)
        {
            var selectedAccount = grdAccounts.SelectedRows.Cast<DataGridViewRow>().FirstOrDefault();
            if (selectedAccount == null) return;

            var pokerName = selectedAccount.Cells["Email"].Value.ToString();

            if (!ValidateBeforePlay(pokerName))
            {
                MessageBox.Show("the Poker " + pokerName + " is in the game. Please select another poker", "Pokerist warning", MessageBoxButtons.OK);
                grdAccounts.Focus();
                return;
            }
            if (LimitUserAccessOneTime()) return;

            var formLogin = this.BrowserGame.Document.Forms[0];

            foreach (HtmlElement item in formLogin.All)
            {
                if (item.Name == "PokeristSignInForm[login]")
                    item.SetAttribute("value", pokerName);
                else if (item.Name == "PokeristSignInForm[password]")
                    item.SetAttribute("value", selectedAccount.Cells["Password"].Value.ToString());
                else if (item.GetAttribute("type") == "submit")
                    item.InvokeMember("click");
            }

            //formLogin.GetElementsByTagName("input").GetElementsByName("PokeristSignInForm[login]")[0].InnerText = pokerName;
            //formLogin.GetElementsByTagName("input").GetElementsByName("PokeristSignInForm[password]")[0].InnerText = selectedAccount.Cells["Password"].Value.ToString();
            //formLogin.InvokeMember("submit");
            grpConfiguration.Enabled = false;

            //this.Text = string.Format("Pokerist - {0} - F2(collapse) .:. F3(Expanse) ::.. Writen by: Mr.Hao - Skype ID: vohaoit - Email: vovanhaovn@gmail.com", pokerName);
            this.Text = string.Format("Pokerist robot - {0}", pokerName);
            Pokerist_Common.PokerTitle = this.Text;

            Pokerist_Common.GameStatus = Pokerist_Common.GAME_STATUS.LOGIN;
        }

        private void btnStart_Click(object sender, EventArgs e)
        {            
            this.Cursor = Cursors.WaitCursor;

            Pokerist_Common.PokerTitle = this.Text;
            
            Pokerist_Common.GameStatus = Pokerist_Common.GAME_STATUS.PLAY;
            if (cboPosition.SelectedIndex == 0)
                Pokerist_Common.GamePosition = Pokerist_Common.GAME_POSITION.LOBBY;
            else
                Pokerist_Common.GamePosition = Pokerist_Common.GAME_POSITION.INGAME;

            Pokerist_Common.Game_Amount = Convert.ToUInt16(slideAmount.Value);
            Pokerist_Common.Game_Raise = Convert.ToUInt16(slideRaise.Value);
            Pokerist_Common.Game_Turn_Fold = Convert.ToUInt16(slideFold.Value);
            Pokerist_Common.CallAny = chkCallAny.Checked;

            Pokerist_Common.NoOfFollowing = 0;
            Pokerist_Common.GAME_DELAY = Convert.ToInt32(txtDelay.Text);
            Pokerist_Common.TOTAL_TURN_RESET = 15;
            Pokerist_Common.TIME_RESUME = 2000;
            
            Pokerist_Common.Poker_Role = radFollow.Checked ? Pokerist_Common.ROLES.FOLLOW : radRaise.Checked ? Pokerist_Common.ROLES.RAISE : Pokerist_Common.ROLES.RAISE_ALWAYS;

            var raisePosX = Convert.ToUInt16(Pokerist_Common.RAISE_MIN_POS_X + Math.Floor((Pokerist_Common.RAISE_MAX_POS_X - Pokerist_Common.RAISE_MIN_POS_X) * Convert.ToInt32(slideRaise.Value) / 100.00));
            Pokerist_Common.RAISE_ICR_POS_X = raisePosX > Pokerist_Common.RAISE_MAX_POS_X ? Pokerist_Common.RAISE_MAX_POS_X : raisePosX;

            SwitchStatusControls();

            tokenSource = new CancellationTokenSource();
            Action playGame = delegate() { this.PlayGame(); };
            taskPlayGame = new Task(playGame, tokenSource.Token);
            
            taskPlayGame.Start();

            this.Cursor = Cursors.Default;
        }

        private void slideRaiseAmount_Scroll(object sender, EventArgs e)
        {
            lblAmount.Text = string.Format("{0}", slideAmount.Value);
            lblRaise.Text = string.Format("{0} %", slideRaise.Value);
            if (slideFold.Value == 0)
                lblFold.Text = "Never";
            else
                lblFold.Text = string.Format("{0}", slideFold.Value);
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            var confirm = MessageBox.Show("Do you want to STOP the Pokerist ?", "Pokerist Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
            if (confirm != System.Windows.Forms.DialogResult.Yes) return;

            this.Cursor = Cursors.WaitCursor;

            Pokerist_Common.GameStatus = Pokerist_Common.GAME_STATUS.PAUSE;            
            tokenSource.Cancel();
            tokenSource = null;
            taskPlayGame = null;

            SwitchStatusControls();

            this.Cursor = Cursors.Default;
        }

        #region "Play game"

        private bool ValidateBeforePlay(string pokerName)
        {
            if (string.IsNullOrEmpty(pokerName)) return false;

            AutoItX3 autoit = new AutoItX3();
            var winExist = autoit.WinExists(string.Format("Pokerist - {0} - F2(collapse) .:. F3(Expanse) ::.. Writen by: Mr.Hao - Skype ID: vohaoit - Email: vovanhaovn@gmail.com", pokerName));

            autoit = null;
            return (winExist == 0);
        }

        private bool LimitUserAccessOneTime()
        {
            Process[] processlist = Process.GetProcesses();

            var noOfAccountLive = processlist.Where(t => t.MainWindowTitle.Contains("F2(collapse) .:. F3(Expanse) ::.. Writen by: Mr.Hao - Skype ID: vohaoit - Email: vovanhaovn@gmail.com")).Count();

            if (noOfAccountLive > Pokerist_Common.LimitAccountLive)
            {
                MessageBox.Show("You just be had 4 live accounts at once time. If you want to play more, please contact administrator.", "Pokerist");
                return true;
            }

            return false;
        }

        private void PlayGame()
        {   
            var noOfTurned = 0;
            //var turnCounter = 0;
            //var isReduceCPU = false;

            while (Pokerist_Common.GameStatus == Pokerist_Common.GAME_STATUS.PLAY)
            {
                if (Pokerist_Common.GamePosition == Pokerist_Common.GAME_POSITION.LOBBY)
                {
                    if (IsInvited())
                    {
                        DoAccept();
                        Pokerist_Common.GamePosition = Pokerist_Common.GAME_POSITION.INGAME;
                        System.Threading.Thread.Sleep(100);
                    }
                    else
                        System.Threading.Thread.Sleep(Pokerist_Common.GAME_DELAY);
                }
                else
                {
                    if (IsReady())
                    {
                        if (Pokerist_Common.Poker_Role == Pokerist_Common.ROLES.RAISE_ALWAYS)
                        {
                            DoRaiseAlways();
                        }
                        else if (noOfTurned < Pokerist_Common.Game_Turn_Fold || Pokerist_Common.Game_Turn_Fold == 0)
                        {
                            if (Pokerist_Common.Poker_Role == Pokerist_Common.ROLES.RAISE)
                            {
                                DoRaise();
                                noOfTurned += 1;
                            }
                            else
                            {
                                if (IsCheck())
                                {
                                    DoCheck();
                                    noOfTurned = 0;
                                }
                                else
                                {
                                    DoFollow();
                                    noOfTurned += 1;
                                }
                            }
                        }
                        else
                        {
                            DoFold();
                            noOfTurned = 0;
                            //turnCounter++;

                            //if (turnCounter >= Pokerist_Common.TOTAL_TURN_RESET)
                            //{
                            //    //isReduceCPU = true;
                            //    break;
                            //}
                        }
                    }
                    
                    System.Threading.Thread.Sleep(Pokerist_Common.GAME_DELAY);
                }
            }

            //if (isReduceCPU) ReduceCPU();
        }

        private void InitForm()
        {
            cboPosition.SelectedIndex = 0;
            Pokerist_Common.Data_FilePath = Path.Combine(Application.StartupPath, @"Data\DataConfig.xml");
            Pokerist_Common.Invited_FilePath = Path.Combine(Application.StartupPath, @"Data\Invited.jpg");
            Pokerist_Common.Ready_FilePath = Path.Combine(Application.StartupPath, @"Data\Ready.jpg");
            Pokerist_Common.Result_FilePath = Path.Combine(Application.StartupPath, @"Data\Result.jpg");
            Pokerist_Common.RaiseTurn_FilePath = Path.Combine(Application.StartupPath, @"Data\RaiseTurn.jpg");
            Pokerist_Common.TurnResult_FilePath = Path.Combine(Application.StartupPath, @"Data\RaiseTurnTemp.jpg");
            Pokerist_Common.Check_FilePath = Path.Combine(Application.StartupPath, @"Data\Check.jpg");

            Pokerist_Common.HANDLER = this.BrowserGame.Handle;
            Pokerist_Common.NoOfFollowing = 0;


            AccessData data = new AccessData();
            DataSet ds = new DataSet();
            var reader = new System.Xml.XmlNodeReader(data.GetData_Pokerist());
            ds.ReadXml(reader);
            grdAccounts.DataSource = ds.Tables[0].DefaultView;
            grdAccounts.Columns["NO"].Width = 30;
            grdAccounts.Columns["Email"].Width = 150;


            lblAmount.Text = slideAmount.Value.ToString();
            lblRaise.Text = string.Format("{0} %", slideRaise.Value);
            if (slideFold.Value == 0)
                lblFold.Text = "Never";
            else
                lblFold.Text = string.Format("{0}", slideFold.Value);
            
            data = null;
        }

        private bool IsInvited()
        {
            if (!File.Exists(Pokerist_Common.Invited_FilePath)) return false;

            var imgInvited = (Bitmap)Bitmap.FromFile(Pokerist_Common.Invited_FilePath);
            if (imgInvited == null) return false;

            var imgResult = CaptureImage(Pokerist_Common.HANDLER, Pokerist_Common.INVITED_IMAGE_POS_X, Pokerist_Common.INVITED_IMAGE_POS_Y, Pokerist_Common.INVITED_WIDTH, Pokerist_Common.INVITED_HEIGH);
            imgResult.Save(Pokerist_Common.Result_FilePath);
            imgResult = Image.FromFile(Pokerist_Common.Result_FilePath);

            var compare = imgInvited.EqualTo(imgResult);
            imgResult.Dispose();
            imgInvited.Dispose();

            return compare;
        }

        private bool IsReady()
        {
            if (!File.Exists(Pokerist_Common.Ready_FilePath)) return false;

            var imgReady = (Bitmap)Bitmap.FromFile(Pokerist_Common.Ready_FilePath);
            if (imgReady == null) return false;

            var imgResult = CaptureImage(Pokerist_Common.HANDLER, Pokerist_Common.READY_IMAGE_POS_X, Pokerist_Common.READY_IMAGE_POS_Y, Pokerist_Common.READY_WIDTH, Pokerist_Common.READY_HEIGH);

            imgResult.Save(Pokerist_Common.Result_FilePath);
            imgResult = Image.FromFile(Pokerist_Common.Result_FilePath);
            var compare = imgReady.EqualTo(imgResult);
            imgResult.Dispose();
            imgReady.Dispose();

            return compare;
        }

        private bool IsRaiseTurn()
        {
            if (!File.Exists(Pokerist_Common.RaiseTurn_FilePath)) return false;

            var imgTurn = (Bitmap)Bitmap.FromFile(Pokerist_Common.RaiseTurn_FilePath);
            if (imgTurn == null) return false;

            var imgResult = CaptureImage(Pokerist_Common.HANDLER, Pokerist_Common.TURN_IMAGE_POS_X, Pokerist_Common.TURN_IMAGE_POS_Y, Pokerist_Common.TURN_WIDTH, Pokerist_Common.TURN_HEIGH);
            imgResult.Save(Pokerist_Common.TurnResult_FilePath);
            imgResult.Dispose();

            imgResult = Image.FromFile(Pokerist_Common.TurnResult_FilePath);

            var compare = imgTurn.EqualTo(imgResult);
            
            imgResult.Dispose();
            imgTurn.Dispose();

            return compare;
        }

        private bool IsCheck()
        {
            if (!File.Exists(Pokerist_Common.Check_FilePath)) return false;

            var imgCheck = (Bitmap)Bitmap.FromFile(Pokerist_Common.Check_FilePath);
            if (imgCheck == null) return false;

            var imgResult = CaptureImage(Pokerist_Common.HANDLER, Pokerist_Common.CHECK_IMAGE_POS_X, Pokerist_Common.CHECK_IMAGE_POS_Y, Pokerist_Common.CHECK_WIDTH, Pokerist_Common.CHECK_HEIGH);
            imgResult.Save(Pokerist_Common.TurnResult_FilePath);
            imgResult.Dispose();

            imgResult = Image.FromFile(Pokerist_Common.TurnResult_FilePath);

            var compare = imgCheck.EqualTo(imgResult);

            imgResult.Dispose();
            imgCheck.Dispose();

            return compare;
        }

        private void DoAccept()
        {
            AutoItX3 autoit = new AutoItX3();

            //click accept button
            autoit.ControlClick(Pokerist_Common.PokerTitle, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", 1, Pokerist_Common.INVITED_POS_X, Pokerist_Common.INVITED_POS_Y);
            autoit.Sleep(15000);

            //click reset amount
            autoit.ControlClick(Pokerist_Common.PokerTitle, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", 10, Pokerist_Common.RESET_DEC_POS_X, Pokerist_Common.RESET_DEC_POS_Y);
            autoit.Sleep(100);

            //click increase amount
            autoit.ControlClick(Pokerist_Common.PokerTitle, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", Pokerist_Common.Game_Amount, Pokerist_Common.RESET_ICR_POS_X, Pokerist_Common.RESET_ICR_POS_Y);
            autoit.Sleep(100);

            //click OK
            autoit.ControlClick(Pokerist_Common.PokerTitle, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", 1, Pokerist_Common.RESET_OK_POS_X, Pokerist_Common.RESET_OK_POS_Y);
            
            autoit = null;
        }

        private void DoRaise()
        {
            AutoItX3 autoit = new AutoItX3();

            //click reset amount
            autoit.ControlClick(Pokerist_Common.PokerTitle, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", 10, Pokerist_Common.RAISE_DEC_POS_X, Pokerist_Common.RAISE_DEC_POS_Y);
            
            //click increase amount
            autoit.ControlClick(Pokerist_Common.PokerTitle, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", Pokerist_Common.Game_Raise, Pokerist_Common.RAISE_ICR_POS_X, Pokerist_Common.RAISE_ICR_POS_Y);
            
            //click RAISE button
            autoit.ControlClick(Pokerist_Common.PokerTitle, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", 1, Pokerist_Common.RAISE_POS_X, Pokerist_Common.RAISE_POS_Y);
            
            //click call any button
            //autoit.ControlClick(Pokerist_Common.PokerTitle, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", 2, Pokerist_Common.FOLLOW_POS_X, Pokerist_Common.FOLLOW_POS_Y);

            autoit = null;
        }

        private void DoRaiseAlways()
        {
            AutoItX3 autoit = new AutoItX3();

            //click RAISE button
            autoit.ControlClick(Pokerist_Common.PokerTitle, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", 1, Pokerist_Common.RAISE_POS_X, Pokerist_Common.RAISE_POS_Y);

            if (Pokerist_Common.CallAny)
                autoit.ControlClick(Pokerist_Common.PokerTitle, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", 2, Pokerist_Common.FOLLOW_POS_X, Pokerist_Common.FOLLOW_POS_Y);

            autoit = null;
        }

        private void DoFollow()
        {
            AutoItX3 autoit = new AutoItX3();

            //click call any/ follow button
            autoit.ControlClick(Pokerist_Common.PokerTitle, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", 1, Pokerist_Common.FOLLOW_POS_X, Pokerist_Common.FOLLOW_POS_Y);
            
            //click CHECK button
            //autoit.ControlClick(Pokerist_Common.PokerTitle, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", 1, Pokerist_Common.CHECK_POS_X, Pokerist_Common.CHECK_POS_Y);
            
            //click raise amount
            //autoit.ControlClick(Pokerist_Common.PokerTitle, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", 1, Pokerist_Common.RAISE_POS_X, Pokerist_Common.RAISE_POS_Y);

            autoit = null;
        }

        private void DoCheck()
        {
            AutoItX3 autoit = new AutoItX3();

            //click CHECK button
            autoit.ControlClick(Pokerist_Common.PokerTitle, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", 1, Pokerist_Common.CHECK_POS_X, Pokerist_Common.CHECK_POS_Y);
            
            autoit = null;
        }

        private void DoFold()
        {
            AutoItX3 autoit = new AutoItX3();

            //click fold button
            autoit.ControlClick(Pokerist_Common.PokerTitle, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", 1, Pokerist_Common.FOLD_POS_X, Pokerist_Common.FOLD_POS_Y);
            
            //click Profile At Seat button
            autoit.ControlClick(Pokerist_Common.PokerTitle, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", 1, Pokerist_Common.LOAD_PROFILE_POS_X, Pokerist_Common.LOAD_PROFILE_POS_Y);
            autoit.Sleep(100);

            //click reset amount button
            autoit.ControlClick(Pokerist_Common.PokerTitle, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", 1, Pokerist_Common.AMOUNT_POS_X, Pokerist_Common.AMOUNT_POS_Y);
            autoit.Sleep(300);

            //click reset amount
            autoit.ControlClick(Pokerist_Common.PokerTitle, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", 10, Pokerist_Common.RESET_DEC_POS_X, Pokerist_Common.RESET_DEC_POS_Y);
            
            //click increase amount
            autoit.ControlClick(Pokerist_Common.PokerTitle, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", Pokerist_Common.Game_Amount, Pokerist_Common.RESET_ICR_POS_X, Pokerist_Common.RESET_ICR_POS_Y);
            
            //click OK
            autoit.ControlClick(Pokerist_Common.PokerTitle, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", 1, Pokerist_Common.RESET_OK_POS_X, Pokerist_Common.RESET_OK_POS_Y);
            autoit.Sleep(500);

            autoit.ControlClick(Pokerist_Common.PokerTitle, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", 1, Pokerist_Common.AMOUNT_OK_POS_X, Pokerist_Common.AMOUNT_OK_POS_Y);
            
            autoit = null;
        }

        private void ReduceCPU()
        {
            Pokerist_Common.GameStatus = Pokerist_Common.GAME_STATUS.PAUSE;

            tokenSource.Cancel();
            tokenSource = null;
            taskPlayGame = null;

            Pokerist_Common.TIME_STOP = DateTime.Now;
        }

        private void ResumeThread()
        {
            Pokerist_Common.TIME_STOP = null;

            Pokerist_Common.GameStatus = Pokerist_Common.GAME_STATUS.PLAY;
            tokenSource = new CancellationTokenSource();
            Action playGame = delegate() { this.PlayGame(); };
            taskPlayGame = new Task(playGame, tokenSource.Token);
            taskPlayGame.Start();
        }

        #endregion

        #region "controls behaviours"

        private void SwitchStatusControls()
        {
            if (Pokerist_Common.GameStatus == Pokerist_Common.GAME_STATUS.LOGIN)
            {
                setEnableButton(btnStart, false);
                setEnableButton(btnStop, false);
                setEnableButton(btnSignOut, false);
                //this.BrowserGame.Document.Window.ScrollTo(this.BrowserGame.Left, this.BrowserGame.Bottom - 250);
            }
            else if (Pokerist_Common.GameStatus == Pokerist_Common.GAME_STATUS.READY)
            {
                setEnableButton(btnSignOut, true);
                setEnableButton(btnStart, true);
                setEnableButton(btnStop, false);
                //setEnableButton(btnPlayGame, false);
                //this.BrowserGame.Document.Window.ScrollTo(this.BrowserGame.Left, this.BrowserGame.Bottom - 250);
            }            
            else if (Pokerist_Common.GameStatus != Pokerist_Common.GAME_STATUS.PAUSE)
            {
                setEnableButton(btnSignOut, false);
                //setEnableButton(btnPlayGame, false);
                setEnableButton(btnStart, false);
                setEnableButton(btnStop, true);
                setEnableGroup(grpGamePlay, false);
                this.BrowserGame.Document.Window.ScrollTo(this.BrowserGame.Left, this.BrowserGame.Bottom - Convert.ToInt32(txtScrollValue.Text));
                //this.BrowserGame.Document.Window.ScrollTo(this.BrowserGame.Left, this.BrowserGame.Bottom - 320);
                //this.BrowserGame.Document.Window.ScrollTo(this.BrowserGame.Left, this.BrowserGame.Bottom - 200);
            }
            else
            {
                setEnableButton(btnSignOut, true);
                //setEnableButton(btnPlayGame, false);
                setEnableButton(btnStart, true);
                setEnableButton(btnStop, false);
                setEnableGroup(grpGamePlay, true);
                this.BrowserGame.Document.Window.ScrollTo(this.BrowserGame.Left, this.BrowserGame.Bottom - Convert.ToInt32(txtScrollValue.Text));
                //this.BrowserGame.Document.Window.ScrollTo(this.BrowserGame.Left, this.BrowserGame.Bottom - 320);
                //this.BrowserGame.Document.Window.ScrollTo(this.BrowserGame.Left, this.BrowserGame.Bottom - 200);
            }
        }

        delegate void SetEnableButtonCallback(Button btn, bool isEnabled);
        private void setEnableButton(Button btn, bool isEnabled)
        {
            if (btn.InvokeRequired)
            {
                SetEnableButtonCallback setEnabled = new SetEnableButtonCallback(setEnableButton);
                this.Invoke(setEnabled, btn, isEnabled);
            }
            else
                btn.Enabled = isEnabled;
        }

        delegate void SetEnableGroupCallback(GroupBox grp, bool isEnabled);
        private void setEnableGroup(GroupBox grp, bool isEnabled)
        {
            if (grp.InvokeRequired)
            {
                SetEnableGroupCallback setEnabled = new SetEnableGroupCallback(setEnableGroup);
                this.Invoke(setEnabled, grp, isEnabled);
            }
            else
                grp.Enabled = isEnabled;
        }

        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            this.BrowserGame.Document.Window.ScrollTo(this.BrowserGame.Left, this.BrowserGame.Bottom - Convert.ToInt32(txtScrollValue.Text));
            //var image = CaptureImage(this.BrowserGame.Handle, Convert.ToInt32(textBox1.Text), Convert.ToInt32(textBox2.Text),
            //    Convert.ToInt32(textBox3.Text), Convert.ToInt32(textBox4.Text));

            //string path = Path.Combine(Application.StartupPath, @"Data\temp.jpg");

            //image.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);

            //image.Dispose();
        }

        #region "proccess images"

        [DllImport("user32.dll")]
        public static extern IntPtr GetWindowDC(IntPtr hWnd);
        [DllImport("gdi32.dll")]
        public static extern bool BitBlt(IntPtr hObject, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hObjectSource, int nXSrc, int nYSrc, int dwRop);
        [DllImport("gdi32.dll")]
        public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth, int nHeight);
        [DllImport("gdi32.dll")]
        public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
        [DllImport("gdi32.dll")]
        public static extern bool DeleteDC(IntPtr hDC);
        [DllImport("gdi32.dll")]
        public static extern bool DeleteObject(IntPtr hObject);
        [DllImport("gdi32.dll")]
        public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
        [DllImport("user32.dll")]
        public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);
        public const int SRCCOPY = 13369376;

        private Image CaptureImage(IntPtr handle, int posX, int posY, int width, int height)
        {            
            IntPtr hdcSrc = GetWindowDC(handle);

            IntPtr hdcDest = CreateCompatibleDC(hdcSrc);
            IntPtr hBitmap = CreateCompatibleBitmap(hdcSrc, width, height);

            IntPtr hOld = SelectObject(hdcDest, hBitmap);
            BitBlt(hdcDest, 0, 0, width, height, hdcSrc, posX, posY, SRCCOPY);
            SelectObject(hdcDest, hOld);
            DeleteDC(hdcDest);
            ReleaseDC(handle, hdcSrc);

            Image image = Image.FromHbitmap(hBitmap);
            DeleteObject(hBitmap);

            return image;
        }

        #endregion

        private void BrowserGame_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            try
            {
                if (this.BrowserGame.IsBusy) return;

                if (Pokerist_Common.GameStatus == Pokerist_Common.GAME_STATUS.PLAY ||
                    Pokerist_Common.GameStatus == Pokerist_Common.GAME_STATUS.PAUSE) return;

                if (this.BrowserGame.Document.GetElementsByTagName("input").GetElementsByName("PokeristSignInForm[login]").Count > 0)
                {
                    grpConfiguration.Enabled = true;
                    Pokerist_Common.GameStatus = Pokerist_Common.GAME_STATUS.LOGIN;

                    SwitchStatusControls();

                    var selectedAccount = grdAccounts.SelectedRows.Cast<DataGridViewRow>().FirstOrDefault();
                    if (selectedAccount == null) return;

                    var formLogin = this.BrowserGame.Document.Forms[0];
                    formLogin.GetElementsByTagName("input").GetElementsByName("PokeristSignInForm[login]")[0].InnerText = selectedAccount.Cells["Email"].Value.ToString();
                    formLogin.GetElementsByTagName("input").GetElementsByName("PokeristSignInForm[password]")[0].InnerText = selectedAccount.Cells["Password"].Value.ToString();
                }
                else if (Pokerist_Common.GameStatus == Pokerist_Common.GAME_STATUS.LOGIN)
                {
                    grpConfiguration.Enabled = false;
                    Pokerist_Common.GameStatus = Pokerist_Common.GAME_STATUS.START;
                    this.BrowserGame.Navigate("http://pokerist.com/en/play-now/");
                }
                else if (Pokerist_Common.GameStatus == Pokerist_Common.GAME_STATUS.SIGNOUT)
                {
                    //setEnableButton(btnPlayGame, true);
                    setEnableGroup(grpConfiguration, true);                    
                    Pokerist_Common.GameStatus = Pokerist_Common.GAME_STATUS.LOGIN;
                    this.BrowserGame.Navigate("http://pokerist.com/en/sign-in/");
                }
                else if (Pokerist_Common.GameStatus == Pokerist_Common.GAME_STATUS.START)
                {
                        Thread.Sleep(2000);

                    Pokerist_Common.GameStatus = Pokerist_Common.GAME_STATUS.READY;

                    SwitchStatusControls();

                    //this.BrowserGame.Navigate("http://pokerist.com/profile/game/");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void timerReduceCPU_Tick(object sender, EventArgs e)
        {
            if (Pokerist_Common.TIME_STOP == null) return;

            ResumeThread();            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            var image = CaptureImage(this.BrowserGame.Handle, Convert.ToInt32(txtScrollValue.Text), Convert.ToInt32(textBox2.Text),
                Convert.ToInt32(textBox3.Text), Convert.ToInt32(textBox4.Text));

            string path = Path.Combine(Application.StartupPath, @"Data\temp.jpg");

            image.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);

            image.Dispose();
        }

        private void btnSignOut_Click(object sender, EventArgs e)
        {
            var confirm = MessageBox.Show("Do you want to sign out the poker?", "Poker pro", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
            if (confirm == System.Windows.Forms.DialogResult.Yes)
            {
                Pokerist_Common.GameStatus = Pokerist_Common.GAME_STATUS.SIGNOUT;
                setEnableButton(btnSignOut, false);
                //setEnableButton(btnPlayGame, true);
                setEnableGroup(grpConfiguration, true);
                this.BrowserGame.Navigate(new Uri("http://pokerist.com/en/sign-out/"));
            }
        }

        private void BrowserGame_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            if (e.KeyCode == Keys.F2)
                ReSizeForm(true);
            else if (e.KeyCode == Keys.F3)
                ReSizeForm(false);
        }

        private void PokeristMain_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F2)
                ReSizeForm(true);
            else if (e.KeyCode == Keys.F3)
                ReSizeForm(false);
        }

        private void ReSizeForm(bool minimize)
        {
            if (minimize)
            {
                //this.grpInfo.Visible = false;
                this.Width = MIN_WIDTH;
            }
            else
            {
                this.Width = MAX_WIDTH;
                //this.grpInfo.Visible = true;
            }
        }

        private void PokeristMain_Shown(object sender, EventArgs e)
        {
            return;

            if (!Pokerist_Common.HasLicensed)
            {
                RegisterProduct formRegister = new RegisterProduct();
                formRegister.ShowDialog();

                if (!Pokerist_Common.HasLicensed) 
                    this.Close();                
            }
            
            if (Pokerist_Common.NetWorkTime == DateTime.MinValue)
            {
                MessageBox.Show("Please double check the internet connection and try again !", "Pokerist");
                this.Close();
            }
            else if (Pokerist_Common.StartPeriod.AddMonths(Pokerist_Common.Period).Date < Pokerist_Common.NetWorkTime.Date)
            {
                MessageBox.Show("Your product has expired. Please contact administrator for purchasing the new license !", "Pokerist");
                this.Close();
            }
        }
    }
}
